from Products.Five import BrowserView
from plone.app.layout.viewlets.common import ViewletBase
from Products.CMFPlone.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from random import randint
from zope.component import getMultiAdapter
from Acquisition import aq_base
from DateTime.DateTime import DateTime

class mainNavigationView(ViewletBase):
    
    index = ViewPageTemplateFile('templates/uriach_navigation.pt')
    portal_tabs = None
    selected_tabs = None
    
    def update(self):
        self.setupTabs()
        
    def setupTabs(self):
        allowedSections = ('copalia','rupafin','disgren','silostar','telo','micetal','ferinject','caphosol','alvesco','vimovo','palladone')
        #import pdb;pdb.set_trace()
        if self.context.getSectionFromURL() == '':
            return False
        if self.context.getSectionFromURL().split('-')[1] not in allowedSections:
            return False
        
        context_state = getMultiAdapter((self.context, self.request),
                                        name=u'plone_context_state')
        actions = context_state.actions()
        portal_tabs_view = getMultiAdapter((self.context, self.request),
                                           name='portal_tabs_view')
        
        #import pdb;pdb.set_trace()
        
        portal_properties = getToolByName(self.context, 'portal_properties')
        navtree_properties = getattr(portal_properties, 'navtree_properties')
        if self.context.getSectionFromURL() != '':
            navtree_properties.root = '/' +  self.context.getSectionFromURL().split('-')[1]
        #self.portal_tabs = portal_tabs_view.topLevelTabs(actions=actions)
        self.portal_tabs = portal_tabs_view.topLevelTabs()

        selectedTabs = self.context.restrictedTraverse('selectedTabs')
        self.selected_tabs = selectedTabs('index_html',
                                          self.context,
                                          self.portal_tabs)
        self.selected_portal_tab = self.selected_tabs['portal']
        
        navtree_properties.root = '/'
        if self.portal_tabs:
            return True
        else:
            return False
        
    def getSubNav(self, id):
        #self.context.plone_log('viewlets, l.25, id='+str(id))
        #import pdb;pdb.set_trace()
        urltool = getToolByName(self.context, 'portal_url')
        portal_catalog = getToolByName(self.context, 'portal_catalog')
        
        #path = urltool.getPortalPath() + '/' + id 
        if self.context.getSectionFromURL() != '':
            path = urltool.getPortalPath() + '/' + self.context.getSectionFromURL().split('-')[1] + '/' + id
        else:
            path = '/'.join(self.context.getPhysicalPath()) + '/' + id
            
        #mypath = path+'/'+id
        mypath = path
        folders = portal_catalog.searchResults(portal_type = ['Folder', 'Ploneboard','PloneboardForum'],
                                         path = dict(query=mypath, depth=1),
                                         review_state=['internally_published','external','published','memberposting','open'],
                                         sort_on='getObjPositionInParent')
        
        #self.context.plone_log('viewlets, l.35, path='+str(path))
        #self.context.plone_log('viewlets, l.36, folders='+str(folders))
        
        if folders is None:
            return False
        else:
            return folders
        
    def isSelected(self, id):
        #self.context.plone_log('viewlets, l.46, isSelected, id='+str(self.context.getId()))
        if self.context.getId() == id:
            return True
        else:
            return False


    def test(self, value, trueVal, falseVal):
        """
            helper method, mainly for setting html attributes.
        """
        if value:
            return trueVal
        else:
            return falseVal
    
    def is_new(self, modified):
        portal_membership = getToolByName(self.context, 'portal_membership')
        llt = getattr(aq_base(self), '_last_login_time', [])
        if llt == []:
            m = portal_membership.getAuthenticatedMember()
            if m.has_role('Anonymous'):
                llt = self._last_login_time = None
            else:
                llt = self._last_login_time = m.getProperty('last_login_time', 0)
        if llt is None: # not logged in
            return False
        elif llt == 0: # never logged in before
            return True
        else:
            return (modified >= DateTime(llt))